<template>
  <el-form
    class="meta-query auto-grid query-grid"
    ref="form"
    :model="form"
    :inline="true"
    :label-position="isMobile ? 'top' : undefined"
    label-width="100px"
    v-if="meta && meta.length > 0"
  >
    <template v-for="(col, idx) in meta">
      <el-form-item
        :inline="true"
        :label="col.name"
        v-if="col.display && col.queryable !== false"
        :key="idx"
        :prop="col.key"
      >
        <el-autocomplete
          v-if="col.type === 'string' && (col.source || col.pinyin_search)"
          :clearable="true"
          v-bind="col.autocomplete"
          v-model="form[col.key]"
          placeholder="请输入"
          :fetch-suggestions="(qs, cb) => inputQuerySearch(qs, cb, col)"
        />
        <el-input
          v-else-if="col.type === 'string'"
          clearable
          v-model="form[col.key]"
          placeholder="请输入"
        />
        <template v-else-if="['int', 'float', 'number'].includes(col.type)">
          <el-input
            class="range-input"
            type="number"
            v-model="form[col.key][0]"
            placeholder="请输入"
          />
          <span style="padding: 0 5px">-</span>
          <el-input
            class="range-input"
            type="number"
            v-model="form[col.key][1]"
            placeholder="请输入"
          />
        </template>
        <el-input
          v-else-if="col.type === 'password'"
          type="password"
          show-password
          clearable
          v-model="form[col.key]"
          placeholder="请输入"
        />
        <el-select
          v-else-if="col.type === 'enum'"
          v-model="form[col.key]"
          clearable
          placeholder="请选择"
        >
          <template v-for="(val, index) in col.values" :key="index">
            <el-option v-if="typeof val === 'object'" :label="val.name" :value="val.key" />
            <el-option v-else :label="val" :value="val" />
          </template>
        </el-select>
        <el-select
          v-else-if="col.type === 'list'"
          filterable
          clearable
          allow-create
          multiple
          collapse-tags
          v-model="form[col.key]"
          placeholder="请选择"
        >
          <template v-for="(val, index) in col.values" :key="index">
            <el-option v-if="typeof val === 'object'" :label="val.name" :value="val.key" />
            <el-option v-else :label="val" :value="val" />
          </template>
        </el-select>
        <el-date-picker
          v-else-if="col.type === 'datetime'"
          clearable
          v-model="form[col.key]"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        />
        <el-input v-else clearable v-model="form[col.key]" placeholder="请输入" />
      </el-form-item>
    </template>
    <template v-if="$slots.default">
      <el-form-item :inline="true">
        <slot name="default" :form="form"></slot>
      </el-form-item>
    </template>
  </el-form>
</template>

<script>
import { getFormValues, getTableList } from '@/api/basic'
import PinyinEngine from 'pinyin-engine'
import { useAppStore } from '@/store/modules/app'

const appStore = useAppStore()

export default {
  name: 'MetaForm',
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    config: {
      type: Object,
      default: () => ({})
    },
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      pinyinEngineData: {}
    }
  },
  computed: {
    form: {
      get: function () {
        return this.modelValue
      },
      set: function (value) {
        this.$emit('update:modelValue', value)
      }
    },
    isMobile() {
      return appStore.getMobile
    }
  },
  watch: {
    meta: {
      handler() {
        this.initFormData()
        // this.initAutocomplete(this.meta)
      },
      immediate: true
    },
    form: {
      handler() {
        this.$emit('change', this.getFormData())
      },
      deep: true,
      immediate: true
    }
  },
  // mounted() {
  //   this.initAutocomplete(this.meta)
  // },
  methods: {
    resetForm() {
      this.form = this.meta.reduce((t, c) => {
        if (['int', 'float', 'number'].includes(c.type)) {
          t[c.key] = []
        }
        return t
      }, {})
      this.initFormData()
      this.$emit('change', {})
    },
    initFormData() {
      this.meta.forEach((m) => {
        if (['int', 'float', 'number'].includes(m.type)) {
          this.form[m.key] = []
        }
      })
    },
    getFormData() {
      const result = {}
      this.meta.forEach((m) => {
        if (this.form[m.key]) {
          if (['int', 'float', 'number'].includes(m.type)) {
            if (this.form[m.key].filter((v) => !!v).length > 0) {
              result[m.key] = this.form[m.key].map((v) => Number(v))
            }
          } else if (['datetime'].includes(m.type)) {
            if (this.form[m.key].filter((v) => !!v).length > 0) {
              result[m.key] = this.form[m.key]
            }
          } else {
            result[m.key] = this.form[m.key]
          }
        }
      })
      return result
    },
    inputQuerySearch(qs, cb, col) {
      let results = []
      if (col.pinyin_search && col._pinyinEngine) {
        results = qs ? col._pinyinEngine.query(qs) : col.values
      } else {
        results = qs ? col.values.filter((x) => `${x.value}`.includes(qs)) : col.values
      }
      cb(results)
    }
  }
}
</script>

<style lang="less" scoped>
.meta-query {
  :deep(.el-input) {
    &.range-input {
      width: 76px;
    }
  }
}
</style>
